app.factory('socket', ['$rootScope', function ($rootScope) {
  var socket;
  var messageTypes = {};
  
  window.addEventListener('beforeunload', function() {
	  if(socket) {
		  socket.send(JSON.stringify({type:'leave'}));
		  socket.close();
	  }
  }, false);
  
  return {
	connect: function(name, room) {
		socket = new WebSocket('ws://localhost:8080/chat/websocket/chat');
		socket.onmessage = function() {
			var args = arguments,
				chatMessage;
			if(args[0] && args[0].data) {
				chatMessage = JSON.parse(args[0].data);
				if(typeof messageTypes[chatMessage.type] === 'function') {
					$rootScope.$apply(function () {
						messageTypes[chatMessage.type].apply(socket, [chatMessage]);
			        });
				}
			}
		};
	},
	onopen: function(callback) {
		socket.onopen = function() {
			var args = arguments;
			$rootScope.$apply(function () {
	          callback.apply(socket, args);
	        });
		};
	},
	onerror: function(callback) {
		socket.onerror = function() {
			var args = arguments;
			$rootScope.$apply(function () {
				callback.apply(socket, args);
	        });
		};
	},
	onmessage: function(type, callback) {
		messageTypes[type] = callback;
	},
	onclose: function() {
		console.log(arguments);
	},
	sendMessage: function(message) {
		socket.send(JSON.stringify(message));
	}
  };
}]);